Handling Dynamic Elements
Why Dynamic Elements Are a Real Problemβ
Dynamic elements change after page load due to:
- AJAX / API calls
- JavaScript re-rendering
- Conditional UI logic
- SPA frameworks (React, Angular, Vue)
Most flaky Selenium tests fail here, not because of bad locators.
Common Dynamic Behaviorsβ
- Element appears/disappears
- Element becomes clickable later
- Text/value changes dynamically
- Element is replaced in DOM
- List size changes
Each behavior needs a different handling strategy.
1. Element Appears After Delayβ
β Wrongβ
driver.findElement(By.id("msg")).click();
β Correctβ
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("msg"))).click();
2. Element Becomes Clickable Laterβ
wait.until(ExpectedConditions.elementToBeClickable(By.id("submit"))).click();
Use this when overlays/loaders block clicks.
3. Waiting for Text or Value Changeβ
wait.until(ExpectedConditions.textToBePresentInElement(
driver.findElement(By.id("status")), "Completed"
));
4. Handling Elements That Disappearβ
Loader / Spinnerβ
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("loader")));
Always wait for disappearance before next action.
5. Re-Locating Replaced Elementsβ
Dynamic frameworks often replace DOM nodes.
wait.until(ExpectedConditions.refreshed(
ExpectedConditions.visibilityOfElementLocated(By.id("profile"))
));
6. Handling Dynamic Lists / Tablesβ
wait.until(ExpectedConditions.numberOfElementsToBeMoreThan(
By.cssSelector(".result-row"), 0
));
Validate count after wait.
7. Avoiding Stale Element Issuesβ
β Store WebElement too early
WebElement btn = driver.findElement(By.id("save"));
β Locate after wait
wait.until(ExpectedConditions.elementToBeClickable(By.id("save"))).click();
What NOT to Do ββ
- Thread.sleep
- Fixed waits
- Blind retries
- Index-based XPath
- Assuming UI timing
Common Mistakes ββ
- Waiting for presence instead of visibility
- Ignoring element replacement
- Using implicit wait as a fix
- Hardcoding delays
- Debugging without logs
Best Practices β β
- Always identify the dynamic behavior type
- Use the correct ExpectedCondition
- Re-locate elements after DOM changes
- Encapsulate waits inside page methods
- Log waits for debugging
Interview Notes π―β
Q: What causes dynamic element issues?
A: Asynchronous UI updates.
Q: How do you handle elements replaced in DOM?
A: Re-locate elements using refreshed conditions.
Q: Best solution for dynamic UI?
A: Explicit waits with correct conditions.
Real-Project Tip π‘β
If a test fails only in CI and not locally, itβs almost always a dynamic timing issue.
Summaryβ
- Dynamic elements are unavoidable
- Correct waits solve most issues
- Element re-location is critical
- Avoid static waits